<template>
  <div style="width:100vw;display:flex;justify-content: center;background:#F9F9F9">
    <div class="container" style="width:75vw">
      <AssignmentNavBar :homeworkId="homeworkId" :semesterId="semesterId" />
      <form @submit.prevent="confirmAndSubmit" style="padding: 20px 30px;background:white;">
        <!-- 发布设置 -->
        <div class="settings-box">
          <p style="font-weight: bold;color: #333333;">发布设置</p>
          <div class="form-group">
            <label for="start_time">开始时间</label>
            <input type="datetime-local" v-model="startTime" id="start_time" :disabled="submitted"/>
            <p style="font-size:14px;color:gray">（学生收到作业的时间）</p>
          </div>
          <div class="form-group">
            <label for="end_time">结束时间</label>
            <input type="datetime-local" v-model="endTime" id="end_time" :disabled="submitted"/>
            <p style="font-size:14px;color:gray">（学生“按时”提交作品的时间截点）</p>
          </div>
        </div>
        <!-- 互评设置 -->
        <div class="settings-box">
          <p style="font-weight: bold;color: #333333;">互评设置</p>
          <div class="form-group checkbox-group">
            <input type="checkbox" v-model="isEach" id="is_each" :disabled="submitted" />
            <label for="is_each">开启互评</label>
          </div>
          <div v-if="isEach" class="form-group">
            <label style="margin-left: 30px;" for="each_cnt">互评数量</label>
            <input type="number" v-model="eachCnt" id="each_cnt" min="0" :disabled="submitted"/>
            <p style="margin: 0;">份</p>
          </div>
          <div v-if="isEach" class="form-group">
            <label style="margin-left: 30px;" for="each_score">缺评扣分</label>
            <input type="number" v-model="eachScore" id="each_score" min="0" :disabled="submitted"/>
            <p style="margin: 0;margin-right: 20px;">分</p>
            <p style="font-size:14px;color:gray">（学生缺评时，其成绩将被扣减的分值）</p>
          </div>
          <div v-if="isEach" class="form-group">
            <label style="margin-left: 30px;" for="each_end">截止时间</label>
            <input type="datetime-local" v-model="eachEnd" id="each_end" :disabled="submitted"/>
            <p style="font-size:14px;color:gray">（学生参与互评的时间截点）</p>
          </div>
        </div>
        <!-- 补交设置 -->
        <div class="settings-box">
          <p style="font-weight: bold;color: #333333;">补交设置</p>
          <div class="form-group checkbox-group">
            <input type="checkbox" v-model="isRemit" id="is_remit" :disabled="submitted" />
            <label for="is_remit">开启补交</label>
          </div>
          <div v-if="isRemit" class="form-group">
            <label style="margin-left: 30px;" for="remit_score">补交扣分</label>
            <input type="number" v-model="remitScore" id="remit_score" min="0" :disabled="submitted"/>
            <p style="margin: 0;">分</p>
             <p style="font-size:14px;color:gray;margin-right: 20px;">（延时提交作品时，学生成绩将被扣减的分值）</p>
          </div>
          <div v-if="isRemit" class="form-group">
            <label style="margin-left: 30px;" for="remit_time">截止时间</label>
            <input type="datetime-local" v-model="remitTime" id="remit_time" :disabled="submitted"/>
             <p style="font-size:14px;color:gray">（学生“延时”提交作品的时间截点）</p>
          </div>
        </div>
        <!-- 评分设置 -->
        <div class="settings-box">
          <p style="font-weight: bold;color: #333333;">评分设置</p>
           <div class="form-group">
            <label for="update_cnt">允许提交次数</label>
            <input type="number" v-model="updateCnt" id="update_cnt" min="1" :disabled="submitted"/>
            <p style="margin: 0;">次</p>
          </div>
          <div class="form-group">
            <label for="tech_weight">教评占比(%)</label>
            <input type="number" v-model="techWeight" id="tech_weight" min="0" max="100" :disabled="submitted"/>
          </div>
          <div class="form-group">
            <label for="admin_weight">助教占比(%)</label>
            <input type="number" v-model="adminWeight" id="admin_weight" min="0" max="100" :disabled="submitted"/>
          </div>
          <div v-if="isEach" class="form-group">
            <label for="each_weight">互评占比(%)</label>
            <input type="number" v-model="eachWeight" id="each_weight" min="0" max="100" :disabled="submitted"/>
          </div>
        </div>
        <p style="font-size:12px;color:gray;margin-left:30px">Tip:作业开始时间必须早于作业截止时间，早于作业补交截止时间，早于互评结束时间</p>
        <!-- 提交和取消按钮 -->
        <div class="form-group button-group">
          <button type="submit" class="submit-button" :disabled="submitted">保存</button>
          <button type="button" class="back-button" @click="$router.go(-1)" :disabled="submitted">取消</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { ElMessage,ElMessageBox  } from 'element-plus';
import { updateAdvancedSettings, getAdvancedSettings } from '@/services/api'; 
import AssignmentNavBar from '@/components/AssignmentNavBar.vue';

export default {
  name: 'AdvancedSettings',
  components: { AssignmentNavBar },
  props: {
    homeworkId: {
      type: [String, Number],
      required: true,
    },
    semesterId: {
      type: [String, Number],
      required: true,
    },
  },
  setup(props) {
    const startTime = ref('');
    const endTime = ref('');
    const updateCnt = ref(3);
    const isEach = ref(false);
    const isRemit = ref(false);
    const remitTime = ref('');
    const remitScore = ref(0);
    const eachEnd = ref('');
    const eachCnt = ref(0);
    const eachScore = ref(0);
    const techWeight = ref(0);
    const adminWeight = ref(0);
    const eachWeight = ref(0);
    
    const submitted = ref(false);

    // 获取已保存的提交状态
    const loadSubmittedStatus = () => {
      const status = localStorage.getItem(`advancedSettingsSubmitted_${props.homeworkId}_${props.semesterId}`);
      submitted.value = status === 'true';
    };

    // 在组件挂载时加载提交状态
    onMounted(async () => {
      loadSubmittedStatus();

      try {
        const response = await getAdvancedSettings(props.homeworkId);
        
        if (response.data && response.data.status === 1) {
          const settings = response.data.data; // 注意这里是获取 data 字段

          // Populate reactive variables with API data
          startTime.value = settings.start_time || '';
          endTime.value = settings.end_time || '';
          updateCnt.value = settings.update_cnt || 3; // 默认值
          isEach.value = settings.is_each || false;
          isRemit.value = settings.is_remit || false;
          remitTime.value = settings.remit_time || '';
          remitScore.value = settings.remit_score || 0;
          eachEnd.value = settings.each_end || '';
          eachCnt.value = settings.each_cnt || 0;
          eachScore.value = settings.each_score || 0;
          techWeight.value = settings.tech_weight || 0;
          adminWeight.value = settings.admin_weight || 0;
          eachWeight.value = settings.each_weight || 0;

          // 如果已提交，禁用输入框
          if (submitted.value) {
            disableInputs();
          }
        }
      } catch (error) {
        console.error('获取高级设置失败:', error);
        ElMessage.error('获取高级设置失败，请稍后重试。');
      }
    });

    const disableInputs = () => {
      submitted.value = true; // 仅标记为已提交
    };

    const validateTimes = () => {
      if (
        new Date(startTime.value) >= new Date(endTime.value) ||
        (isRemit.value && new Date(endTime.value) >= new Date(remitTime.value)) ||
        (isEach.value && new Date(eachEnd.value) <= new Date(remitTime.value))
      ) {
        ElMessage.error('时间设置不正确，请检查！');
        return false;
      }
      return true;
    };

    const confirmAndSubmit = async () => {
       if (!validateTimes()) return;

      try {
        // 替换原生confirm为ElMessageBox
        await ElMessageBox.confirm('请检查所有设置是否正确，确认后将保存。', '确认提交', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        const settings = {
          homework_id: props.homeworkId,
          start_time: startTime.value,
          end_time: endTime.value,
          update_cnt: updateCnt.value,
          is_each: isEach.value,
          is_remit: isRemit.value,
          remit_time: isRemit.value ? remitTime.value : null,
          remit_score: isRemit.value ? remitScore.value : 0,
          each_end: isEach.value ? eachEnd.value : null,
          each_cnt: isEach.value ? eachCnt.value : 0,
          each_score: isEach.value ? eachScore.value : 0,
          tech_weight: techWeight.value,
          admin_weight: adminWeight.value,
          each_weight: isEach.value ? eachWeight.value : 0,
        };

        const response = await updateAdvancedSettings(settings);
        if (response.data.status === 1) {
          ElMessage.success('高级设置已成功保存！');
          submitted.value = true;
          localStorage.setItem(`advancedSettingsSubmitted_${props.homeworkId}_${props.semesterId}`, 'true');
          disableInputs();
        } else {
          console.error('保存高级设置失败，错误信息:', response.data.msg);
          ElMessage.error(`保存失败: ${response.data.msg}`);
        }
      } catch (error) {
        console.error('保存高级设置失败:', error);
        ElMessage.error('保存高级设置失败，请稍后重试。');
      }
    };

    return {
      startTime,
      endTime,
      updateCnt,
      isEach,
      isRemit,
      remitTime,
      remitScore,
      eachEnd,
      eachCnt,
      eachScore,
      techWeight,
      adminWeight,
      eachWeight,
      confirmAndSubmit,
      submitted,
    };
  },
};
</script>

<style scoped>
  .container {
  width: 100vw;
  background: #F9F9F9;
  padding: 20px;
  padding-top: 0px;
}

.navbar {
  display: flex;
  gap: 20px;
  background-color: #ffffff;
  padding: 15px 30px;
}


.settings-box h2 {
  font-weight: bold;
  margin-bottom: 15px;
}
.settings-box{
  border-bottom: 1px solid rgb(237, 237, 237);
}

.form-group {
  display: flex;
  flex-direction: row;
  align-items: baseline;
  justify-content: flex-start;
  margin: 10px 20px 20px 30px;
}

.checkbox-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

label {
  font-size: 14px;
}

input[type='text'],
input[type='datetime-local'] {
     padding: 5px 10px;
    font-size: 16px;
    border: 1px solid #ccc;
    border-radius: 3px;
    width: 15%;
    margin: 0px 20px;
}

input[type='number'] {
   padding: 5px 10px;
    font-size: 16px;
    border: 1px solid #ccc;
    border-radius: 3px;
    width: 5%;
    margin: 0px 10px 0px 20px;
}
.button-group {
  display: flex;
  gap: 20px;
}

.submit-button {
  background-color: #244382;
  color: #fff;
  padding: 10px 40px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
.submit-button:hover {
  background-color: #3e66b0;
}
.back-button {
  background-color: #f0f0f0;
  color: #333;
  padding: 10px 40px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
.back-button:hover {
  background-color: rgb(201, 200, 200);
}
.cancel-button {
  background-color: #f44336;
  color: white;
  padding: 12px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  width: 100%;
}

.cancel-button:hover {
  background-color: #e53935;
}
button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
